package cn.yunhe.webSocket;

import cn.yunhe.entity.Emp;
import org.apache.log4j.Logger;

import javax.servlet.http.HttpSession;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

@ServerEndpoint(value = "/handler.do",configurator = WebSocketConfig.class)
public class WebSocketHandler {

    static private Logger logger = Logger.getLogger(WebSocketHandler.class);

    // 连接集合 userId => server 键值对 线程安全
    static public final ConcurrentMap<String, WebSocketHandler> map = new ConcurrentHashMap<>();

    // 与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;

    // 当前会话的httpsession
    private HttpSession httpSession;

    @OnOpen
    public void onOpen(Session session, EndpointConfig config) {

        // 得到httpSession
        this.httpSession = (HttpSession) config.getUserProperties().get(HttpSession.class.getName());

        // 获取session对象 SObject(这个就是java web登入后的保存的session对象，此处为用户信息，包含了euuid)
        Emp emp= (Emp) this.httpSession.getAttribute("emp");

        this.session = session;

        // 将连接session对象存入map
        map.put(emp.getEuuId(), this);

    }

    @OnClose
    public void onClose() {

        /**
         * 获取当前连接信息 {@code CommonConstant.USER_LOGIN_SESSION} 为Http session 名
         */
        Emp emp= (Emp) this.httpSession.getAttribute("emp");
        // 移除连接
        map.remove(emp.getEuuId());

    }

    @OnMessage
    public void onMessage(String message) throws IOException {
        //信息处理未添加
    }


    /**
     * 创建服务器的定点信息推送
     */
    public static void pushBySys(String uuid)  {
        WebSocketHandler socket=map.get(uuid);
        if(socket!=null){
            try {
                socket.session.getBasicRemote().sendText("101");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }




}
